package manager.orders.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import common.SnowflakeIdWorker;
import manager.auth.vo.UserInfo;
import manager.config.AuthInteceptor;
import manager.orders.dao.OrderDetialMapper;
import manager.orders.dao.OrderMapper;
import manager.orders.dao.OrderStatusMapper;
import manager.orders.service.OrderService;
import manager.orders.vo.OrderDetialVO;
import manager.orders.vo.OrderStatus;
import manager.orders.vo.OrderVO;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetialMapper orderDetialMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;
    @Transactional
    @Override
    public void addOrder(OrderVO orderVO) {
            //添加订单
            String orderId=String.valueOf(SnowflakeIdWorker.nextId());
            orderVO.setOrderId(orderId);
            orderVO.setCreateTime(new Date());
            String shippingCode=String.valueOf(SnowflakeIdWorker.nextId());
            orderVO.setShippingCode(shippingCode);
            orderMapper.insertSelective(orderVO);
            orderVO.getOrderDetialList().forEach(item->{
                String orderItemId=String.valueOf(SnowflakeIdWorker.nextId());
                item.setId(orderItemId);
                item.setOrderId(orderId);
            });
            orderDetialMapper.insertList(orderVO.getOrderDetialList());
            //设置订单状态信息
            orderVO.getOrderStatus().setOrderId(orderId);
            orderVO.getOrderStatus().setCreateTime(new Date());
            orderStatusMapper.insert(orderVO.getOrderStatus());
            //扣减库存
            amqpAdmin.declareExchange(new DirectExchange("crmshop.stock.exchange"));
            amqpAdmin.declareQueue(new Queue("crmshop.stock.queen",true));
            amqpAdmin.declareBinding(new Binding("crmshop.stock.queen", Binding.DestinationType.QUEUE,"crmshop.stock.exchange","stock.update.decrease",null));
            amqpTemplate.convertAndSend("crmshop.stock.exchange", "stock.update.decrease", orderVO.getOrderDetialList());
    }

    @Override
    public PageInfo<OrderVO> getOrderByCondition(OrderVO orderVO) {
           Example example = new Example(OrderVO.class);
           Example.Criteria criteria = example.createCriteria();
           UserInfo userInfo= AuthInteceptor.getUserInfo();
           criteria.andEqualTo("buyerNick",userInfo.getUsername());
           PageHelper.startPage(orderVO.getPageInfo().getPageNum(),orderVO.getPageInfo().getPageSize());
           List<OrderVO> orderVoList=orderMapper.selectByExample(example);
           List<String> orderIdList=orderVoList.stream().map(OrderVO::getOrderId).collect(Collectors.toList());
           List<OrderStatus> orderStatusList=getOrderStatus(orderIdList);
           List<OrderDetialVO> orderDetialVOS=getOrderDetialVoList(orderIdList);
           orderVoList.forEach(item->{
                 //设置订单项
                 List<OrderDetialVO> orderDetialVOList=orderDetialVOS.stream().filter(curItem->curItem.getOrderId().equals(item.getOrderId())).collect(Collectors.toList());
                 item.setOrderDetialList(orderDetialVOList);
                 //设置订单状态
                 List<OrderStatus> orderStatuses=orderStatusList.stream().filter(curItem->curItem.getOrderId().equals(item.getOrderId())).collect(Collectors.toList());
                 if(orderStatuses.size()>0){
                     item.setOrderStatus(orderStatuses.get(0));
                 }
           });
           PageInfo<OrderVO> pageInfo = new PageInfo<OrderVO>(orderVoList);
           return pageInfo;
    }

    /**
     * 查询订单详情
     * @param orderIdList
     * @return
     */
    private List<OrderDetialVO> getOrderDetialVoList(List<String> orderIdList){
            Example example = new Example(OrderDetialVO.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("orderId",orderIdList);
            return orderDetialMapper.selectByExample(example);
    }

    /**
     * 查询订单状态
     * @param orderIdList
     */
    public List<OrderStatus> getOrderStatus(List<String> orderIdList){
            Example example = new Example(OrderStatus.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("orderId",orderIdList);
            return orderStatusMapper.selectByExample(example);
    }
    @Transactional
    //删除订单
    @Override
    public void deleteOrder(OrderVO orderVO) {
          deleteOrderMain(orderVO);
          deleteOrderDetial(orderVO);
          deleteOrderMain(orderVO);
    }

    /**
     * 刪除订单项
     */
    private void deleteOrderDetial(OrderVO orderVO){
        Example example = new Example(OrderDetialVO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderVO.getOrderId());
        orderStatusMapper.deleteByExample(example);
    }
    /**
     * 删除订单主项
     * @param orderVO
     */
    private void deleteOrderMain(OrderVO orderVO){
            Example example = new Example(OrderVO.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId",orderVO.getOrderId());
            orderMapper.deleteByExample(example);
    }
    @Override
    public void updateOrder(OrderVO orderVO) {
           Example example = new Example(OrderStatus.class);
           Example.Criteria criteria = example.createCriteria();
           criteria.andEqualTo("orderId",orderVO.getOrderStatus().getOrderId());
           orderStatusMapper.updateByExampleSelective(orderVO.getOrderStatus(),example);
    }
}
